package com.ztmao.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztmao.shortlink.admin.common.constant.RedisCacheConstant;
import com.ztmao.shortlink.admin.convention.errorcode.BaseErrorCode;
import com.ztmao.shortlink.admin.convention.exception.ClientException;
import com.ztmao.shortlink.admin.convention.exception.ServiceException;
import com.ztmao.shortlink.admin.convention.result.Result;
import com.ztmao.shortlink.admin.convention.result.Results;
import com.ztmao.shortlink.admin.dao.entity.UserDO;
import com.ztmao.shortlink.admin.dao.mapper.UserMapper;
import com.ztmao.shortlink.admin.dto.req.UserLoginReqDTO;
import com.ztmao.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.ztmao.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.ztmao.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.ztmao.shortlink.admin.dto.resp.UserRespDTO;
import com.ztmao.shortlink.admin.service.GroupService;
import com.ztmao.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ztmao.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;

/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    private final RedissonClient redissonClient;
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final UserMapper userMapper;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;
    @Override
    public Result getUserByUserName(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username);
        UserDO userDO = userMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ServiceException(BaseErrorCode.USER_NAME_VERIFY_ERROR);
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return Results.success(result);
    }

    @Override
    public Boolean hasUserName(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public Result<Void> register(UserRegisterReqDTO userRegisterReqDTO) {
        //判断是否存在用户名
        if (hasUserName(userRegisterReqDTO.getUsername())) {
            throw new ClientException(BaseErrorCode.USER_NAME_EXIST_ERROR);
        }
        //防止同时间大量请求同时注册一个未存在用户名使用分布式锁使得注册请求串行化
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + userRegisterReqDTO.getUsername());
        //未获取锁则直接返回失败
        if (!lock.tryLock()) {
            throw new ClientException(BaseErrorCode.USER_NAME_EXIST_ERROR);
        }
        try {

            //获取到锁直接进行注册逻辑

            int insert = userMapper.insert(BeanUtil.toBean(userRegisterReqDTO, UserDO.class));
            if (insert < 1) {
                throw new ClientException(BaseErrorCode.USER_REGISTER_ERROR);
            }
            groupService.save(userRegisterReqDTO.getUsername(),"默认分组");
            userRegisterCachePenetrationBloomFilter.add(userRegisterReqDTO.getUsername());

        } finally {
            lock.unlock();
        }
        return Results.success();
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        //todo 判断用户的请求与修改的用户是否一致
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), updateWrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {

        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException("用户不存在");
        }
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        /**
         * Hash
         * Key：login_用户名
         * Value：
         *  Key：token标识
         *  Val：JSON 字符串（用户信息）
         */
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY + requestParam.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }
}
